package com.wuwei.chatServer.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wuwei.chatServer.result.Result;
import com.wuwei.chatServer.utils.EncryptUtil;
import com.wuwei.chatServer.utils.GetUserInfoUtil;
import com.wuwei.chatServer.utils.JwtUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value="/admin")
public class ApiController {

    @Autowired
    JwtUtil jwtUtil;

    @GetMapping("onLogin/{code}")
    public Result login (@PathVariable String code)   {
        //通过code换取信息
        JSONObject resultJson = GetUserInfoUtil.getResultJson(code);
        if (resultJson.get("openid")!=null){
            //获取sessionKey和openId
            String sessionKey = resultJson.get("session_key").toString();
            String openid = resultJson.get("openid").toString();

            //生成自定义登录态session
            String session = null;
            Map<String,String> sessionMap = new HashMap<>();

            sessionMap.put("sessionKey",sessionKey);
            sessionMap.put("openid",openid);
            session = JSONObject.toJSONString(sessionMap);

            //加密session
            try {
                EncryptUtil encryptUtil = new EncryptUtil();
                session = encryptUtil.encrypt(session);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //生成token
            String token = jwtUtil.getToken(session);
            Map<String,String> result = new HashMap<>();
            result.put("token", token);
//
//            //查询用户是否存在
//            Owner owner = ownerService.queryOwnerInfo(openid);
//            if (owner != null){
//                return Result.succ("登录成功", result); //用户存在，返回结果
//            }else { //用户不存在，新建用户信息
//                int rs = ownerService.insertOwner(openid);
//                if (rs <= 0){
//                    return Result.fail("登录失败");
//                }
//                return Result.succ("登录成功", result);
//            }
            return Result.ok(result);
        }
        return Result.fail(null);
    }

    public static CloseableHttpClient createSSLClientDefault() throws Exception{
        //如果下面的方法证书还是不过，报错的话试试下面第二种
        /* SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy(){
        //信任所有
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        return true;
        }
        }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();*/

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                NoopHostnameVerifier.INSTANCE);
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();

    }
}
